package com.yxw.yx_hotel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yxw.yx_hotel.dto.user.*;
import com.yxw.yx_hotel.entity.YxHotelTenantEntity;
import com.yxw.yx_hotel.entity.YxSysUserEntity;
import com.yxw.yx_hotel.exception.GlobalCustomerException;
import com.yxw.yx_hotel.mapper.HotelTenantMapper;
import com.yxw.yx_hotel.mapper.UserMapper;
import com.yxw.yx_hotel.service.UserService;
import com.yxw.yx_hotel.utils.AssertUtil;
import com.yxw.yx_hotel.utils.PageUtils;
import com.yxw.yx_hotel.utils.StringUtil;
import com.yxw.yx_hotel.utils.UserUtil;
import com.yxw.yx_hotel.vo.UserAccountVO;
import com.yxw.yx_hotel.vo.UserCenterInfoVO;
import com.yxw.yx_hotel.vo.UserTokenVo;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.ErrorCodeEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author fangmaoxin
 * @version 1.0
 * @date 2024年1月24日
 * 登录账号管理相关
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, YxSysUserEntity> implements UserService {

    @Autowired
    private HotelTenantMapper hotelTenantMapper;

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserUtil  userUtil;

    /**
     * 查询登录账号列表
     */
    @Override
    public PageVO<UserAccountVO> getUserAccountList(Long userId, UserAccountQueryDTO dto) {
        UserTokenVo userVo = userUtil.getLoginUserVo();
        userId = userVo.getUserId();
        if(userVo.getUserType() == 2)
        {
            dto = new UserAccountQueryDTO();
            dto.setUserType(2);
        }
        else
        {
            dto.setTenantId(userVo.getTenantId());
            dto.setUserType(null);        
        }
        //AssertUtil.isNotNull(userId, ErrorCodeEnum.USER_ID_ERROR);
        Page<YxSysUserEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        List<UserAccountVO> result = userMapper.getUserAccountList(page, userId, dto);
        return PageUtils.get(page, result);
    }

    /**
     * 添加登录账号-子账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUserAccount(UserAccountAddDTO dto) {
        UserTokenVo userVo = userUtil.getLoginUserVo();
        YxSysUserEntity majorUser = userMapper.selectById(userVo.getUserId());
        AssertUtil.isNotNull(majorUser, ErrorCodeEnum.USER_ID_ERROR);
        if (!Integer.valueOf(1).equals(majorUser.getUserType())) {
            throw new GlobalCustomerException(ErrorCodeEnum.NOT_MAJOR_USER_CANNOT_ADD_USER);
        }
        // 校验手机号和登录账号是否重复
        YxSysUserEntity mobilePhone = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("mobile_phone", dto.getMobilePhone()));
        AssertUtil.isNull(mobilePhone, ErrorCodeEnum.PHONE_IS_REGISTERED);
        YxSysUserEntity userNum = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("user_num", dto.getUserNum()));
        AssertUtil.isNull(userNum, ErrorCodeEnum.USER_NUM_IS_EXISTS);
        YxSysUserEntity user = getYxSysUserEntity(dto,userVo);
        userMapper.insert(user);
        Long userId = user.getUserId();
        String newPassword = PasswordUtil.signUserPassword(userId, dto.getPassword());
        LambdaUpdateWrapper<YxSysUserEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(YxSysUserEntity::getUserId, userId)
                .set(YxSysUserEntity::getPassword, newPassword);
        userMapper.update(null, updateWrapper);
    }

    private YxSysUserEntity getYxSysUserEntity(UserAccountAddDTO dto,UserTokenVo userVo) {
        YxSysUserEntity user = new YxSysUserEntity();
        user.setMobilePhone(dto.getMobilePhone());
        user.setPassword(dto.getPassword());
        user.setUserNum(dto.getUserNum());
        user.setUserStatus(dto.getUserStatus());
        user.setParentUserId(dto.getLoginUserId());
        user.setUserName(dto.getUserName());
        user.setCreateTime(new Date());
        user.setUserType(3);
        if (null != dto.getDeptId()) {
            user.setDeptId(dto.getDeptId());
        }
        if (null != dto.getPostId()) {
            user.setPostId(dto.getPostId());
        }
        if (null != dto.getRoleId()) {
            user.setRoleId(dto.getRoleId());
        }
        user.setCreateUserId(userVo.getUserId());
        user.setCreateUserName(userVo.getUserName());
        user.setTenantId(userVo.getTenantId());
        /*
        user.setCreateUserId(dto.getLoginUserId());
        YxSysUserEntity selectOne = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("user_id", dto.getLoginUserId()));
        if (null != selectOne && null != selectOne.getUserName()) {
            user.setCreateUserName(selectOne.getUserName());
            if (null != selectOne.getTenantId()) {
                user.setTenantId(selectOne.getTenantId());
            }
        }
        */
        return user;
    }

    /**
     * 修改账号信息-子账户
     */
    @Override
    public void updateUserAccount(UserAccountUpdateDTO dto) {
        
        // 判断当前操作人是不是该子账户的主账户
        YxSysUserEntity user = userMapper.selectById(dto.getUserId());
        if (null != user) {
            AssertUtil.isEquals(String.valueOf(user.getParentUserId()), String.valueOf(dto.getLoginUserId()), ErrorCodeEnum.ILLEGAL_OPERATION);
            // 判断手机号和登录账号是否已注册
            YxSysUserEntity phone = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("mobile_phone", dto.getMobilePhone()).ne("user_id", dto.getUserId()));
            AssertUtil.isNull(phone, ErrorCodeEnum.PHONE_IS_REGISTERED);
            YxSysUserEntity userNum = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("user_num", dto.getUserNum()).ne("user_id", dto.getUserId()));
            AssertUtil.isNull(userNum, ErrorCodeEnum.USER_NUM_IS_EXISTS);
        }
        if (null != dto.getPassword()) {
            String newPassword = PasswordUtil.signUserPassword(dto.getUserId(), dto.getPassword());
            dto.setPassword(newPassword);
        }
        userMapper.updateUserAccount(dto);
    }


    /**
     * 删除账号信息-子账户
     */
    @Override
    public void deleteUserAccount(UserAccountDeleteDTO dto) {
        // 判断当前操作人是不是该子账户的主账户
        YxSysUserEntity user = userMapper.selectById(dto.getUserId());
        if (null != user) {
            AssertUtil.isEquals(String.valueOf(user.getParentUserId()), String.valueOf(dto.getLoginUserId()), ErrorCodeEnum.ILLEGAL_OPERATION);
        }
        // 删除子账户
        userMapper.deleteById(dto.getUserId());
    }

    /**
     * 个人中心-查询账号信息
     */
    @Override
    public UserCenterInfoVO getUserCenterInfo(UserCenterInfoQueryDTO dto) {
        AssertUtil.isNotNull(dto.getUserId(), ErrorCodeEnum.USER_ID_ERROR);
        UserCenterInfoVO vo = new UserCenterInfoVO();
        YxSysUserEntity user = userMapper.selectById(dto.getUserId());
        if (null != user) {
            vo.setUserId(user.getUserId());
            vo.setUserNum(StringUtil.isNotEmpty(user.getUserNum()) ? user.getUserNum() : null);
            vo.setPicUrl(StringUtil.isNotEmpty(user.getPicUrl()) ? user.getPicUrl() : null);
            vo.setMobilePhone(StringUtil.isNotEmpty(user.getMobilePhone()) ? user.getMobilePhone() : null);
            vo.setPassword(StringUtil.isNotEmpty(user.getPassword()) ? user.getPassword() : null);
            if (null != user.getCreateTime()) {
                vo.setCreateTime(user.getCreateTime());
            }
            if (null == user.getParentUserId() && null != user.getUserType() && Integer.valueOf(1).equals(user.getUserType())) { // 如果上级id等于空，证明是主账户
                YxHotelTenantEntity entity = hotelTenantMapper.selectById(user.getTenantId());
                vo.setWholeName(StringUtil.isNotEmpty(entity.getWholeName()) ? entity.getWholeName() : null);
            } else if (null != user.getParentUserId() && null != user.getUserType() && Integer.valueOf(3).equals(user.getUserType())) { // 如果为子账户，则拿父级账号查
                YxSysUserEntity parent = userMapper.selectById(user.getParentUserId());
                if (null != parent && null != parent.getTenantId()) {
                    YxHotelTenantEntity entity = hotelTenantMapper.selectById(parent.getTenantId());
                    vo.setWholeName(StringUtil.isNotEmpty(entity.getWholeName()) ? entity.getWholeName() : null);
                }
            }
        }
        return vo;
    }

    /**
     * 个人中心-修改账号信息
     */
    @Override
    public void updateUserCenterInfo(UserCenterInfoUpdateDTO dto) {
        // 如果当前登录人不是需要修改的本人，报错
        AssertUtil.isEquals(String.valueOf(dto.getLoginUserId()), String.valueOf(dto.getUserId()), ErrorCodeEnum.ILLEGAL_OPERATION);
        // 修改手机号
        if (null != dto.getMobilePhone()) {
            // 判断手机号是否已注册
            YxSysUserEntity phone = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("mobile_phone", dto.getMobilePhone()).ne("user_id", dto.getUserId()));
            AssertUtil.isNull(phone, ErrorCodeEnum.PHONE_IS_REGISTERED);
        }
        // 修改密码
        if (null != dto.getPassword() && null != dto.getConfirmPassword()) {
            // 判断新密码和确认密码是否一致
            if (!Objects.equals(PasswordUtil.signUserPassword(dto.getUserId(), dto.getPassword()), PasswordUtil.signUserPassword(dto.getUserId(), dto.getConfirmPassword()))) {
                throw new BaseException("新密码和确认密码不一致！");
            } else {
                String newPassword = PasswordUtil.signUserPassword(dto.getUserId(), dto.getPassword());
                dto.setPassword(newPassword);
            }
        } else {
            dto.setPassword(null);
        }
        userMapper.updateUserCenterInfo(dto);
    }
}
